from pathlib import Path
from getpass import getpass
from rich import print

home = Path.home()
env = home / '.config' / 'shellgpt' / '.env'

BANNER = '''
███████╗██╗  ██╗███████╗██╗     ██╗          ██████╗ ██████╗ ████████╗
██╔════╝██║  ██║██╔════╝██║     ██║         ██╔════╝ ██╔══██╗╚══██╔══╝
███████╗███████║█████╗  ██║     ██║         ██║  ███╗██████╔╝   ██║   
╚════██║██╔══██║██╔══╝  ██║     ██║         ██║   ██║██╔═══╝    ██║   
███████║██║  ██║███████╗███████╗███████╗    ╚██████╔╝██║        ██║   
╚══════╝╚═╝  ╚═╝╚══════╝╚══════╝╚══════╝     ╚═════╝ ╚═╝        ╚═╝   
'''

def read_config(encoding: str='utf-8', comment_prefix: str | tuple=('#', ';')) -> dict:
    """### Read `.env` file"""
    with open(env, 'r', encoding=encoding) as config_file:
        config_dict = {}
        configs = config_file.readlines()
        configs = [conf.strip() for conf in configs if conf.strip()]
        configs = [conf for conf in configs if not conf.startswith(comment_prefix)]
        for conf in configs:
            k, v = conf.split('=')
            config_dict[k] = v
    return config_dict

def write_config(config: dict, encoding: str='utf-8') -> None:
    """### Write `.env` file"""
    with open(env, 'w', encoding=encoding) as config_file:
        for k, v in config.items():
            config_file.write(f'{k}={v}\n')

def init_env() -> None:
    """### Initialize `.env` file"""
    if not env.exists():
        env.parent.mkdir(parents=True, exist_ok=True)
        config = {}
        config['openai_api_key'] = getpass('\033[1;35mEnter your OpenAI API key:\033[0m ')
        config['deepseek_api_key'] = getpass('\033[1;35mEnter your DeepSeek API key:\033[0m ')
        config['tongyi_api_key'] = getpass('\033[1;35mEnter your Tongyi API key:\033[0m ')
        config['openai_base_url'] = 'https://api.openai.com/v1'
        config['deepseek_base_url'] = 'https://api.deepseek.com/v1'
        config['tongyi_base_url'] = 'https://dashscope.aliyuncs.com/compatible-mode/v1'
        config['ollama_base_url'] = 'http://127.0.0.1:11434'
        write_config(config)
        print(f'[bold green]Environment variables saved to [bold cyan]`{env}`[/]')
    else:
        print(f'[bold cyan]`{env}` [bold red]already exsists[/]')
